package org.wangnian.validationdemo.validator;

import org.wangnian.validationdemo.validator.annotation.InEnum;
import org.wangnian.validationdemo.validator.enums.BasicEnum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class InEnumValidator implements ConstraintValidator<InEnum,Object> {
    private Class<? extends BasicEnum> enumType;

    @Override
    public void initialize(InEnum inEnum) {
        enumType = inEnum.enumType();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        if (object == null) {
            return true;
        }

        if (enumType == null || !enumType.isEnum()) {
            return false;
        }

        for (BasicEnum basicEnum : enumType.getEnumConstants()) {
            if (basicEnum.getCode().equals(object)){
                return true;
            }
        }
        return false;
    }
}
